﻿
//javascript:var s = document.createElement('script'), d = document; s.src = 'http://theo-sp-tdsp.appspot.com/TDSP/Theo.SP.TDSP.js';d.body.appendChild(s);void (0);

/**
* Theo.SharePoint.TDSP
* ---
* @author: Theodore Shi
* @mail: theodore_shi@hotmail.com
* @version: 0.1
* @updated: 2012-3-10
* ---
* Note: Read the README!
**/

(function () {
    "use strict";

    var TDSP = {
        count: 0,
        isNewFormOpened: false,
        fields: [],
        images: [],
        init: function () {
            var a = $('#s4-workspace'), html = [];
            if (a.length == 0) {
                TDSP.log('Theo.SharePoint.TDSP init error');
                return;
            }
            $('#tdspToolbar').remove();

            html = ['<link href="http://theo-sp-tdsp.appspot.com/TDSP/Theo.SP.TDSP.css" rel="stylesheet" type="text/css" />',
                    '<script src="http://theo-sp-tdsp.appspot.com/TDSP/Theo.SP.TDSP.Data.Base.js"></script>',
                    '<div id="tdspToolbar">',
                        '<div class="logo">',
                            '<a href="http://theo-sp-tdsp.appspot.com/">',
                                '<img src="http://theo-sp-tdsp.appspot.com/TDSP/logo.png" alt="Theo.SP.TDSP" title="Theo.SP.TDSP" />',
                            '</a>',
                            '<br />SP2010 TestData Generator',
                        '</div>',
                        '<div id="tdspConsole">',
                            '<ul></ul>',
                        '</div>',
                        '<div id="rightbar">',
                            '<button id="btnInsert" title="Insert Items" disabled>Insert</button>',
                            '<button id="btnClear" title="Clear All Items" disabled>Clear</button>',
                            '<button id="btnExport" title="Export Items" disabled>Export</button>',
                            '<div id="AreaExportImport" title="Drag here to Import">Import</div>',
                            '<div>',
                                '<div id="btnCollapse">&#8722;</div>',
                            '</div>',
                        '</div>',
                    '</div>'];

            $('#s4-workspace').append(html.join(''));

            $('#tdspToolbar #btnInsert').click(function () {
                var num = prompt('Please type number of items inserted', '10');
                TDSP.log('Waiting for inserting items.');
                if (num && parseInt(num) > 0) {
                    TDSP.insertSPItems(parseInt(num));
                }
            });

            $('#tdspToolbar #btnCollapse').click(function () {
                //$('#tdspToolbar
            });

            TDSP._csomGetListTitle();

            TDSP.log('Theo.SharePoint.TDSP init completely.');

            setInterval(TDSP.checkNewItemForm, 500);
        },

        log: function (msg, type) {
            var cont = $('#tdspToolbar #tdspConsole > ul'),
                line = TDSP.format("<li{0}>{1} : {2}</li>\r\n", type ? (type == 1 ? " class = 'warning'" : " class = 'error'") : "", (new Date).toLocaleTimeString(), msg);
            if (cont.length > 0) {
                cont.append(line);
                cont.scrollTop(cont.prop('scrollHeight') - cont.outerHeight());
            }
            TDSP.count++;
        },

        checkNewItemForm: function () {
            var iframe = $('.ms-dlgFrameContainer iframe').contents();

            if ($('.ms-dlgFrameContainer').length == 1 && $('#onetIDListForm', iframe).length == 1 && !TDSP.isNewFormOpened) {
                TDSP.log('New Item Form is opened.');
                TDSP.log('The fields parsing is starting...');
                setTimeout(TDSP.parseSPFields, 300);
                TDSP.isNewFormOpened = true;
                $('#tdspToolbar #btnInsert').prop('disabled', false);
            }
            else if (TDSP.isNewFormOpened && $('.ms-dlgFrameContainer').length == 0) {
                TDSP.log('New Item Form is closed.');
                TDSP.isNewFormOpened = false;
                $('#tdspToolbar #btnInsert').prop('disabled', true);
            }
        },

        parseSPFields: function () {
            var iframe = $('.ms-dlgFrameContainer iframe').contents(),
                a = $('.ms-formtable .ms-formbody', iframe),
                b = $('.ms-formtoolbar', iframe),
                c = $('#s4-ribbonrow', iframe),
                i = 0, r, p = /".+"/gi,
                fieldName, fieldInternalName, fieldType;
            if (a.length > 0) {
                for (; i < a.length; i++) {
                    r = a.eq(i)[0].innerHTML.match(p);
                    if (r.length > 3 && a.eq(i).parent().css('display') != 'none') {
                        fieldName = TDSP.replaceAll(r[0], '"', '');
                        fieldInternalName = TDSP.replaceAll(r[1], '"', '');
                        fieldType = TDSP.replaceAll(r[2], '"', '');

                        TDSP.fields.push({
                            FieldName: fieldName,
                            FieldInternalName: fieldInternalName,
                            FieldType: fieldType,
                            Source: TDSP.getFieldValue(a.eq(i), fieldType),
                            DataType: ""
                        });

                        a.eq(i).html(TDSP.buildDataTypeControl(fieldType));
                    }
                }
                b.hide();
                c.find('#s4-ribboncont').hide();
                c.css({
                    height: '40px'
                });
                c.append('<h3 style="padding: 10px; color:#fff">Please select test data type for each field.</h3>');
                TDSP.log('The fields parsing is done.');
            }
        },

        buildDataTypeControl: function (type) {
            var h = ['<span><select>'], i = 0, a;

            if (TDSP.DataType[type] != null && !$.isEmptyObject(TDSP.DataType[type])) {

                h.push('<option value="0">Not Configured</option>');

                for (a in TDSP.DataType[type]) {
                    h.push('<option value="' + a + '">' + a + '</option>');
                }
            }
            else {
                h.push('<option value="0">Not Supported</option>');
            }
            h.push('</span></select>');

            return h.join();
        },

        getFieldValue: function (d, type) {
            var r = [], i = 0, ops;
            switch (type) {
                case "SPFieldChoice":
                case "SPFieldMultiChoice":
                    ops = d.find('option');
                    if (ops.length > 0) {
                        for (i = 0; i < ops.length; i++) {
                            r.push(ops.eq(i).val());
                        }
                    }

                    ops = d.find('tr');
                    if (ops.length > 0) {
                        for (i = 0; i < ops.length; i++) {
                            r.push($.trim(ops.eq(i).text()));
                        }
                    }

                    break;
                case "SPFieldLookup":
                case "SPFieldLookupMulti":
                    ops = d.find('option');
                    if (ops.length > 0) {
                        for (i = 0; i < ops.length; i++) {
                            ops.eq(i).val() != 0 && r.push(ops.eq(i).val());
                        }
                    }
                    break;
            }

            return r;
        },

        insertSPItems: function (num) {
            var iframe = $('.ms-dlgFrameContainer iframe').contents(),
                a = $('.ms-formtable .ms-formbody select', iframe),
                b = $('.ms-formtable #onetIDListForm input', iframe),
                i = 0;

            if (a.length > 0 && a.length == TDSP.fields.length) {
                for (; i < a.length; i++) {
                    TDSP.fields[i].DataType = a.eq(i).val();
                }
            }

            b.prop('disbaled', true);

            TDSP._csomAddSPItem(1, num);
        },

        _listTitle: "",

        _csomAddSPItem: function (index, sum) {
            if (sum - index < 0) {
                TDSP.log(TDSP.format('{0} items have been inserted completely.', sum));
                return;
            }
            var clientContext = new SP.ClientContext.get_current(),
            targetList = clientContext.get_web().get_lists().getByTitle(TDSP._listTitle),
            itemCreateInfo = new SP.ListItemCreationInformation(),
            newListItem = targetList.addItem(itemCreateInfo),
            i = 0;

            for (; i < TDSP.fields.length; i++) {
                if (TDSP.fields[i].DataType != '0') {
                    newListItem.set_item(TDSP.fields[i].FieldInternalName, TDSP.DataType[TDSP.fields[i].FieldType][TDSP.fields[i].DataType](TDSP.fields[i].Source));
                }
            }

            newListItem.update();
            clientContext.load(newListItem);

            clientContext.executeQueryAsync(
            (function (newItem, i) {
                return function () {
                    TDSP.log(TDSP.format('The {0}th item(Id = {1}) was inserted, remaining {2}', index, newItem.get_id(), sum - index));
                    TDSP._csomAddSPItem(index + 1, sum);
                }
            })(newListItem, index),
            function (sender, args) {
                TDSP.log('Request failed. ' + args.get_message() + ' | ' + args.get_stackTrace());
            });
        },

        _csomGetListTitle: function () {
            var clientContext = new SP.ClientContext.get_current(), web, listCollection;
            if (clientContext != undefined && clientContext != null) {
                web = clientContext.get_web();
                listCollection = web.get_lists();
                clientContext.load(listCollection);
                clientContext.executeQueryAsync((function (listCol) {
                    return function () {
                        var listEnumerator = listCol.getEnumerator(),
                href = document.location.href.toLowerCase(), list, url;
                        while (listEnumerator.moveNext()) {
                            list = listEnumerator.get_current();
                            url = list.get_defaultViewUrl().split('/');
                            url.pop();
                            url = url.join('/').toLowerCase() + '/';

                            if (href.indexOf(url) != -1) {
                                TDSP._listTitle = list.get_title();
                                break;
                            }
                        }
                        if (!TDSP._listTitle) {
                            TDSP.log('ERROR: Request failed, can not locate the current list');
                            $('#tdspToolbar #console').css('color', 'yellow');
                        }

                    };
                })(listCollection),
                function onQueryFailed(sender, args) {
                    TDSP.log('Request failed. ' + args.get_message() + ' | ' + args.get_stackTrace());
                });
            }
        },

        DataType: {
            SPFieldText: {},
            SPFieldNote: {},

            SPFieldChoice: {
                'Random': function (a) {
                    if (a) {
                        return a[TDSP.random(0, a.length - 1)];
                    }
                }
            },

            SPFieldMultiChoice: {
                'Random': function (a) {
                    var l = a && a.length - 1, n, r = [], t;
                    if (a) {
                        n = TDSP.random(1, l);
                        while (n) {
                            t = a[TDSP.random(0, l)];
                            if (r.indexOf(t) == -1) {
                                r.push(t);
                                n--;
                            }
                        }
                        return ';#' + r.join(';#') + ';#';
                    }
                }
            },

            SPFieldLookup: {
                'Random': function (a) {
                    if (a) {
                        var f = new SP.FieldLookupValue();
                        return f.set_lookupId(a[TDSP.random(0, a.length - 1)]);
                    }
                }
            },

            SPFieldLookupMulti: {
                'Random': function (a) {
                    var l = a && a.length - 1, n, r = [], t, f;
                    if (a) {
                        n = TDSP.random(1, l);
                        while (n) {
                            t = a[TDSP.random(0, l)];
                            if (r.indexOf(t) == -1) {
                                f = new SP.FieldLookupValue();
                                f.set_lookupId(t);
                                r.push(f);
                                n--;
                            }
                        }
                        return r;
                    }
                }
            },

            SPFieldNumber: {
                'Positive Integer': function () {
                    var s = TDSP.random(1, 8);
                    return TDSP.random(1, Math.pow(10, s));
                },
                'Negative Integer': function () {
                    var s = TDSP.random(1, 8);
                    return TDSP.random(1, Math.pow(10, s)) * -1;
                },
                'Double': function () {
                    var s = TDSP.random(1, 8);
                    return (parseFloat(TDSP.random(1, Math.pow(10, s))) * Math.random()).toFixed(TDSP.random(1, 5));
                },
                'Percentage': function () {
                    return Math.random().toFixed(2);
                }
            },

            SPFieldDateTime: {
                'Date': function () {
                    var y = TDSP.random(1970, 2050),
                        m = TDSP.random(0, 11),
                        d = m != 2 ? TDSP.random(1, 30) : TDSP.random(1, 28);
                    return (new Date(y, m, d));
                },
                'Datetime': function () {
                    var y = TDSP.random(1970, 2050),
                        m = TDSP.random(0, 11),
                        d = m != 2 ? TDSP.random(1, 30) : TDSP.random(1, 28),
                        h = TDSP.random(1, 24),
                        mm = TDSP.random(1, 60),
                        s = TDSP.random(1, 60);
                    return (new Date(y, m, d, h, mm, s));
                }
            },

            SPFieldBoolean: {
                'Random': function () {
                    return TDSP.random(1, 2) == 1 ? 'true' : 'false';
                }
            },

            SPFieldURL: {},

            SPFieldCurrency: {},

            SPFieldUser: {}
        },

        random: function (min, max) {
            return parseInt(Math.random() * (max - min + 1) + min);
        },

        replaceAll: function (s, s1, s2) {
            return s.replace(new RegExp(s1, "gm"), s2);
        },

        format: function (str) {
            var args = Array.prototype.slice.call(arguments);
            if (str === undefined || args.length < 2) return str || "";
            args.shift();
            return str.replace(/\{(\d+)\}/g,
                        function (m, i) {
                            return args[i];
                        });
        },

        extend: function (name, fieldType, implement) {
            if (TDSP.DataType[fieldType]) {
                for (var i = 0; i < implement.length; i++) {
                    TDSP.DataType[fieldType][implement[i].name] = implement[i].get;
                }
                TDSP.log('The data resource "' + name + '" loaded completely.');
            }
        }
    };
    window.TDSP = TDSP;
})();

(function () {
    "use strict";

    function jqLoading(a, b) {
        if (typeof $ != 'undefined') {
            $(function () {
                TDSP.init();
            });
        } else {
            if (!a) {
                var s = document.createElement('script'), d = document;
                s.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
                d.body.appendChild(s);
                a = true;
            }
            setTimeout(
                (function () {
                    return function () {
                        b(a, b);
                    };
                })(), 100);
        }
    };
    jqLoading(false, jqLoading);
})();



